<template>
  <div class="user-edit-container">
    <h2>{{ id ? "编辑" : "新增" }}</h2>
    <el-form ref="formRef" :model="form" label-width="100px" :rules="rules">
      <el-form-item label="任务名称" prop="scriptName">
        <el-input v-model="form.taskName" />
      </el-form-item>
      <el-form-item label="所属脚本" prop="taskContent" style="height: 100%">
        <el-select
          v-model="scriptValue"
          placeholder="请选择脚本"
          style="width: 240px"
          @change="scriptValueChange()"
        >
          <el-option
            v-for="item in scriptOptions"
            :key="item.scriptId"
            :label="item.scriptName"
            :value="item.scriptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务描述" prop="scriptDes">
        <el-input v-model="form.scriptDes" />
      </el-form-item>
      <el-form-item label="任务内容" prop="scriptContent" style="height: 100%">
        <div class="jcsb w100">
          <div class="w50">
            <monacoEditor
              v-model:modelValue="form.scriptContent"
              :scriptForm="form"
              :scriptValue="scriptDataValue"
              @runCode="runCode"
            >
            </monacoEditor>
          </div>

          <div class="dynamics-nat">
            <dynamicsNat
              :disabled="false"
              ref="dynamicsNatRef"
              v-model:modelValue="form.scriptParam"
              v-model:newScriptId="form.scriptId"
              :scriptValue="scriptValue"
              :scriptForm="form"
            ></dynamicsNat>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="运行结果" prop="scriptContent" style="height: 100%">
        <div class="d-f w100">
          <div style="width: 50%">
            <div class="preview-container">
              <div class="preview-header">
                <span>控制台输出</span>
                <el-button @click="genStaRes()">生成静态资源</el-button>
              </div>
              <div class="console-output">
                <div class="console-title">终端输出</div>
                <div>{{ consoleOutput }}</div>
              </div>
            </div>
          </div>
          <imageFrame :src="consoleImge"></imageFrame>
        </div>
      </el-form-item>
      <!-- <el-form-item label="请求参数" prop="scriptDes">
        <dynamicsNat
          :disabled="false"
          ref="dynamicsNatRef"
          v-model:modelValue="form.scriptParam"
          v-model:newScriptId="form.scriptId"
          :scriptForm="form"
        ></dynamicsNat>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { gmtScriptinfo, gmtScriptinfopage } from "@/api/gmtScript";
import {
  gmtTaskinfo,
  gmtTaskExcute,
  gmtTaskinfosaveParam,
  gmtTaskinfoUpdate,
  gmtTaskDebugInfo,
} from "@/api/gmtTask";
import { resourceinfosave, resourceinfosaveText } from "@/api/naturalRes";
import { ElMessage } from "element-plus";
import dynamicsNat from "./dynamicsNat.vue";
import imageFrame from "../gmtScriptView/imageFrame.vue";
import monacoEditor from "./monacoEditor.vue";

const router = useRouter();
const route = useRoute();
const id = ref(route.params.id);
const dynamicsNatRef = ref(null);
const formRef = ref(null);
const consoleOutput = ref();
const consoleImge = ref();
const form: any = reactive({});
const scriptValue = ref("");
const scriptDataValue = ref({});
const scriptOptions = ref();

const rules = reactive({
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
  ],
  age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
  address: [
    {
      required: true,
      message: "请输入地址",
      trigger: "blur",
      resText: "请输入",
    },
  ],
});

// 如果是编辑，加载用户数据
onMounted(async () => {
  const res: any = await gmtScriptinfopage({
    pageNum: 1,
    pageSize: 10,
    orderBy: {},
    conditions: [
      {
        column: "scriptName",
        type: "like",
        value: "",
      },
    ],
    asc: true,
  });
  scriptOptions.value = res.records;
  if (id.value && id.value !== "0" && id.value != "add") {
    loadUserData();
  } else {
    const mockData = {
      scriptId: "",
      scriptName: "",
      scriptDes: "",
      scriptContent: `#!/bin/bash\n`,
    };
    Object.assign(form, mockData);
  }
});

//脚本选择
const scriptValueChange = async () => {
  const scriptData: any = await gmtScriptinfo(scriptValue.value);
  scriptDataValue.value = scriptData;
  if (route.params.id == "add") {
    form.taskParam = scriptData.scriptParam;
  }
};
// 加载用户数据
const loadUserData = async () => {
  const mockData: any = await gmtTaskinfo(id.value);
  const scriptData: any = await gmtScriptinfo(route.params.scriptId);
  const taskData: any = await gmtTaskDebugInfo(id.value);
  consoleImge.value = taskData.imgUrl;
  consoleOutput.value = taskData.excuteLog;
  scriptDataValue.value = scriptData;
  scriptValue.value = scriptData.scriptId;
  console.log("mockData", mockData, form);
  mockData.scriptParam = mockData.scriptParam;
  form.scriptParam = mockData.scriptParam;
  //   mockData.taskParam = JSON.parse(mockData.taskParam);
  Object.assign(form, mockData);
};

//运行代码
const runCode = async () => {
  await gmtTaskinfoUpdate({
    taskId: form.taskId,
    taskName: form.taskName,
    taskDes: form.taskDes,
    // scriptContent: form.scriptContent,
  });
  await gmtTaskinfosaveParam({
    taskId: form.taskId,
    scriptId: form.scriptId,
    scriptParam: form.scriptParam,
  });
  const data: any = await gmtTaskExcute(form.taskId);
  consoleImge.value = data.imgUrl;
  consoleOutput.value = data.excuteLog;
};

//生成静态资源
const genStaRes = async () => {
  const data = await resourceinfosave({
    resName: form.taskName,
    dynamic: 0,
    resType: "1002",
    resDes: form.scriptDes,
  });
  await resourceinfosaveText({
    resId: data,
    resText: `<p><img src=\"${consoleImge.value}"></p>`,
  });
};

// 提交表单
const submitForm = async () => {
  await dynamicsNatRef.value.saveData();
  try {
    await formRef.value.validate();
    if (route.params.id != "add") {
      await gmtTaskinfoUpdate({
        taskId: form.taskId,
        taskName: form.taskName,
        taskDes: form.taskDes,
        // scriptContent: form.scriptContent,
      });
      await gmtTaskinfosaveParam({
        taskId: form.taskId,
        scriptId: form.scriptId,
        scriptParam: form.scriptParam,
      });
    } else {
      await gmtTaskinfoUpdate({
        taskId: form.taskId,
        taskName: form.taskName,
        taskDes: form.taskDes,
        // scriptContent: form.scriptContent,
      });
      await gmtTaskinfosaveParam({
        taskId: form.taskId,
        scriptId: form.scriptId,
        scriptParam: form.scriptParam,
      });
    }

    // API请求
    router.push({
      name: "GMT-script",
    });
  } catch (error) {
    console.log("表单验证失败", error);
  }
};

// 运行动态任务
const runForm = async () => {
  // try {
  //   await formRef.value.validate();
  //   if (route.params.id != "add") {
  //     await gmtScriptinfoUpdate({
  //       resId: form.resId,
  //       resName: form.resName,
  //       resDes: form.resDes,
  //       resType: form.resType,
  //       dynamic: form.dynamic,
  //     });
  //   }
  //   if (form.dynamic == 1) {
  //     await dynamicsNatRef.value.saveData();
  //   } else {
  //     await gmtScriptinfosave({
  //       resId: form.resId,
  //       resText: form.resText,
  //     });
  //   }
  //   loadUserData();
  // } catch (error) {
  //   console.log("表单验证失败", error);
  // }
};

const handleClick = (id) => {
  console.log("id", id);
  // id.value = id;
  form.resId = id;
};

// 取消编辑
const cancel = () => {
  router.push({
    name: "GMT-script",
  });
};

//代码编辑器
</script>

<style scoped>
.user-edit-container {
  padding: 20px;
}
.button-row {
  display: flex;
  justify-content: flex-end; /* 右对齐 */
  width: 100%;
  margin: 10px 0;
}

.button-row button {
  padding: 6px 12px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.preview-container {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
  overflow: hidden;
  display: flex;
  margin-right: 30px;
  flex-direction: column;
}
.editor-header,
.preview-header {
  padding: 16px 20px;
  background: rgba(236, 240, 241, 0.8);
  border-bottom: 1px solid rgba(189, 195, 199, 0.5);
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.preview-content {
  padding: 20px;
  font-family: "Fira Code", "Courier New", monospace;
  white-space: pre-wrap;
  flex: 1;
  overflow: auto;
  background: #2d2d2d;
  color: #f8f8f2;
  line-height: 1.5;
}
.console-output {
  background: #1e1e1e;
  color: #f8f8f2;
  padding: 15px;
  border-radius: 6px;
  margin: 15px;
  font-family: "Fira Code", "Courier New", monospace;
  /* min-height: 200px; */
  height: 100%;
  overflow: auto;
}
.console-title {
  color: #00b09b;
  margin-bottom: 8px;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
  gap: 8px;
}
.dynamics-nat {
  width: 50%;
}
</style>
